package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.dp;

import com.alibaba.cirtus.ots.application.adapter.ability.model.features.ScItemSpecRelFeatures;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.BaseScItemSpecDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.NormalScItemSpecDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.MnScItemUnitInfoSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.DubboResult;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.ResultUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.model.item.scitemspec.ScItemSpecGroupSDO;
import com.alibaba.cz.base.model.item.scitemspec.ScItemSpecSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineAddItemSpecRequest;
import com.epoch.app.bcorder.model.dto.BaselineEditItemSpecRequest;
import com.epoch.app.bcorder.model.dto.BaselineQueryItemSpecListRequest;
import com.epoch.app.bcorder.model.dto.BaselineQueryItemSpecListResponse;
import com.epoch.app.bcorder.model.dto.BaselineQueryRelationSpecRequest;
import com.epoch.app.bcorder.model.dto.BaselineQueryRelationSpecResponse;
import com.epoch.app.bcorder.model.dto.BaselineQueryScItemByPageFromDbRequest;
import com.epoch.app.bcorder.model.dto.BaselineScItemSpecPublishSwitchRequest;
import com.epoch.app.bcorder.model.dto.BaselineScItemSpecRelEditSwitchRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.domain.scitemunit.dto.CreateScItemUnitResponse;
import com.epoch.app.crplatformenhance.domain.scitemunit.dto.ScItemUnitLoadListRequest;
import com.epoch.app.crplatformenhance.domain.scitemunit.dto.UpdateScItemUnitResponse;
import com.epoch.app.crplatformenhance.domain.scitemunit.model.ScItemUnit;
import com.epoch.app.crplatformenhance.domain.scitemunit.service.ScItemUnitService;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.otsapplicationadaptersdk.dp.DpUnitConversion;
import com.epoch.app.otsapplicationadaptersdk.dp.MnDataUnitConversionResponse;
import com.epoch.app.otsapplicationadaptersdk.dp.MnDataUnitConversionSDO;
import com.epoch.app.otsapplicationadaptersdk.dp.mndataif005.dto.DoHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.dp.mndataif005.service.MnDataIf005Service;
import com.epoch.app.otsapplicationadaptersdk.model.dto.ItemCenterDataChangeMessageRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.RestDpUnitConversionDataRequest;
import com.epoch.app.otsapplicationadaptersdk.service.DpService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 单位和单位转换关系
 */
@Component
public class MnDataIf005V2ServiceImpl implements MnDataIf005Service {
    private final Log log = Log.getLogger(MnDataIf005V2ServiceImpl.class);

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private ScItemUnitService scItemUnitService;

    @Resource
    private DpService dpService;


    @Override
    public MnDataUnitConversionResponse doHandler$callAPI(RestDpUnitConversionDataRequest input) {
        return MnDataIf005Service.super.doHandler$callAPI(input);
    }

    @ProcessInvoker(remark = "MnDataIf005Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    @Override
    public Object doHandler(DoHandlerRequest doHandlerRequest) {
        // 构造中台查询参数
        RestDpUnitConversionDataRequest param = buildMnQueryMap(doHandlerRequest);
        // 调用中台接口获取单位转换关系数据（分页信息）
        MnDataUnitConversionSDO mnDataUnitConversionSDO = getResultListMap(param);
        if (mnDataUnitConversionSDO == null || CollectionUtils.isEmpty(mnDataUnitConversionSDO.getRows())) {
            return mnDataUnitConversionSDO;
        }
        Integer totalNum = mnDataUnitConversionSDO.getTotalNum();
        Integer pageSize = mnDataUnitConversionSDO.getPageSize();
        int pageTotalNum = totalNum / pageSize;
        int remainder = totalNum % pageSize;
        if (remainder != 0) {
            pageTotalNum = pageTotalNum + 1;
        }
        // 分页同步货品单位转换关系主数据
        for (int i = 1; i <= pageTotalNum; i++) {
            param.setPageNum(String.valueOf(i));
            log.info("查询单位转换同步参数={},分页数={}", JSON.toJSONString(param), i);
            MnDataUnitConversionSDO dataUnitConversionSDO = getResultListMap(param);
            log.info("单位转换分页查询结果={},分页数={}", JSON.toJSONString(dataUnitConversionSDO), i);
            List<DpUnitConversion> mnScItemUnitInfoList = convertToMnScItemUnitInfo(dataUnitConversionSDO);
            if (CollectionUtils.isEmpty(mnScItemUnitInfoList)) {
                continue;
            }
            // 同步
            syncCurrentPageOfScItemUnitInfo(mnScItemUnitInfoList);
        }
        return mnDataUnitConversionSDO;
    }

    /**
     * 构造查询参数
     * @return
     */
    private RestDpUnitConversionDataRequest buildMnQueryMap(DoHandlerRequest doHandlerRequest) {
        String ds = doHandlerRequest.getDs();
        RestDpUnitConversionDataRequest restDpUnitConversionDataRequest = RestDpUnitConversionDataRequest.builder()
                .fromSys(doHandlerRequest.getFromSys())
                .pageNum(doHandlerRequest.getPageNum())
                .pageSize(doHandlerRequest.getPageSize())
                .build();
        if(StringUtils.isNotBlank(ds)) {
            restDpUnitConversionDataRequest.setDs(ds);
        }
        return restDpUnitConversionDataRequest;
    }

    /**
     * 获取蒙牛单位转换关系主数据
     * 单次拉取不成功，重试10次
     * @param param
     * @return
     */
    private MnDataUnitConversionSDO getResultListMap(RestDpUnitConversionDataRequest param) {
        MnDataUnitConversionResponse mnDataUnitConversionResponse = null;
        int retryTimes = 0;
        String errCode = null;
        do {
            if(ErrorCodeConstant.RATE_LIMIT.equals(errCode)) {
                try {
                    Thread.sleep(120000);
                } catch (InterruptedException e) {
                    log.error("MnDataIf005ServiceImpl#doHandler InterruptedException", e);
                }
            }
            try {
                mnDataUnitConversionResponse = dpService.restDpUnitConversionData(param);
            } catch (Exception e) {
                log.error("MnData_rest_req_occur_exception,restDpUnitConversionData_errorMsg={}",e.getMessage());
                throw e;
            }
            errCode = mnDataUnitConversionResponse.getErrCode();
        } while (!"0".equals(errCode) && retryTimes ++ < 10);
        return mnDataUnitConversionResponse.getData();
    }

    /**
     *  mapToObject
     * @param mnDataUnitConversionSDO
     * @return
     */
    private List<DpUnitConversion> convertToMnScItemUnitInfo(MnDataUnitConversionSDO mnDataUnitConversionSDO) {
        List<DpUnitConversion> dpScItemUnitInfoList = mnDataUnitConversionSDO.getRows();
        return dpScItemUnitInfoList;
    }

    private void syncCurrentPageOfScItemUnitInfo(List<DpUnitConversion> dpScItemUnitInfoList) {
        for (DpUnitConversion dpUnitConversion : dpScItemUnitInfoList) {
            // 数据转换
            MnScItemUnitInfoSDO mnScItemUnitInfoSDO = convertToMnScItemUnitInfoSDO(dpUnitConversion);
            try {
                // 同步单位转换关系
                Boolean result= saveScItemUnitInfo(mnScItemUnitInfoSDO);
            } catch (Exception e) {
                log.error("MnDataIf005ServiceImpl_doHandler_sync_fail_error ", e);
                log.error("MnDataIf005ServiceImpl_doHandler_sync_fail_mnScItemUnitInfoSDO={},error={}", JSON.toJSONString(mnScItemUnitInfoSDO),e);
            }
        }
    }

    /**
     * 货品单位转换关系主数据转换
     * @param dpUnitConversion
     */
    private MnScItemUnitInfoSDO convertToMnScItemUnitInfoSDO(DpUnitConversion dpUnitConversion) {
        MnScItemUnitInfoSDO mnScItemUnitInfoSDO = new MnScItemUnitInfoSDO();
        mnScItemUnitInfoSDO.setOutId(StringUtils.isBlank(dpUnitConversion.getMatnr()) ? "" : dpUnitConversion.getMatnr().trim());
        String unitCode = "";
        if (!StringUtils.isBlank(dpUnitConversion.getMeinh())) {
            unitCode = dpUnitConversion.getMeinh().trim();
            if ("ST".equals(unitCode)) {
                unitCode = "PC";
            }
        }
        mnScItemUnitInfoSDO.setUnitCode(unitCode);
        mnScItemUnitInfoSDO.setUnitName(StringUtils.isBlank(dpUnitConversion.getMeinhdesc()) ? "" : dpUnitConversion.getMeinhdesc().trim());
        mnScItemUnitInfoSDO.setDenominator(StringUtils.isBlank(dpUnitConversion.getUmren()) ? "" : dpUnitConversion.getUmren().trim());
        mnScItemUnitInfoSDO.setConversion(StringUtils.isBlank(dpUnitConversion.getUmrez()) ? "" : dpUnitConversion.getUmrez().trim());
        mnScItemUnitInfoSDO.setUnitDesc(StringUtils.isBlank(dpUnitConversion.getMeinhdesc1()) ? "" : dpUnitConversion.getMeinhdesc1().trim());
        mnScItemUnitInfoSDO.setInternationalBarCode(StringUtils.isBlank(dpUnitConversion.getEan11()) ? "" : dpUnitConversion.getEan11().trim());
        return mnScItemUnitInfoSDO;
    }

    /**
     * 同步单位（转换关系）数据
     */
    private Boolean saveScItemUnitInfo(MnScItemUnitInfoSDO mnScItemUnitInfoSDO) {
        // 1、根据物料编码查询货品存在否
        String outId = mnScItemUnitInfoSDO.getOutId();
        // 1、查询货品
        BaselineQueryScItemByPageFromDbRequest baselineQueryScItemByPageRequest = new BaselineQueryScItemByPageFromDbRequest();
        baselineQueryScItemByPageRequest.setOutIdList(Lists.newArrayList(outId));
        //baselineQueryScItemByPageRequest.setStatusList(Lists.newArrayList(1));
        Object queryScItemByPage = baseDataService.baselineQueryScItemByPageFromDb(baselineQueryScItemByPageRequest);
        DubboResult result = ResultUtils.getDubboPageResult((Map) queryScItemByPage);
        List<Map<String,Object>> scItemList = (List<Map<String, Object>>) result.getResult();
        if(CollectionUtils.isEmpty(scItemList)) {
            // 下一次循环 continue
            log.info("MnDataIf005V2ServiceImpl_queryScItem_is_null,outId={}", outId);
            return false;
        }
        Map<String, Object> stringObjectMap = scItemList.get(0);
        ScItemSDO scItemSDO = JSON.parseObject(JSON.toJSONString(stringObjectMap), ScItemSDO.class);
        // 保存单位
        String unitId = saveScItemUnit(mnScItemUnitInfoSDO);
        // 规格组
        String specGroupId = saveScItemSpecGroup(scItemSDO);
        // 单位转换关系
        return saveOrUpdateScItemSpecRel(specGroupId, scItemSDO, mnScItemUnitInfoSDO);
    }

    /**
     * 报错或者更新单位转换关系
     * @param specGroupId
     * @param scItemSDO
     * @param mnScItemUnitInfoSDO
     * @return
     */
    private Boolean saveOrUpdateScItemSpecRel(String specGroupId, ScItemSDO scItemSDO, MnScItemUnitInfoSDO mnScItemUnitInfoSDO) {
        if (StringUtils.isBlank(specGroupId)) {
            log.info("MnDataIf005V2ServiceImpl_saveOrUpdateScItemSpecRel_specGroupId_is_null");
            return false;
        }
        BaselineQueryRelationSpecRequest baselineQueryRelationSpecRequest = new BaselineQueryRelationSpecRequest();
        baselineQueryRelationSpecRequest.setSpecGroupId(specGroupId);
        BaselineQueryRelationSpecResponse baselineQueryRelationSpecResponse = baseDataService.baselineQueryRelationSpec(baselineQueryRelationSpecRequest);
        if (null == baselineQueryRelationSpecResponse || null == baselineQueryRelationSpecResponse.getResult()) {
            log.info("MnDataIf005V2ServiceImpl_saveOrUpdateScItemSpecRel_queryRelationSpec_error,specGroupId={}", specGroupId);
            return false;
        }
        Map specMap = (Map) baselineQueryRelationSpecResponse.getResult();
        // 拿到规格转换关系列表
        List<Map<String, Object>> scItemSpecSDOList = (List<Map<String, Object>>) specMap.get("scItemSpecSDOList");
        if (CollectionUtils.isEmpty(scItemSpecSDOList)) {
            // 查不到  新增单位转换关系的基本规格（发布规格接口，只有基本规格信息）
            BaselineScItemSpecPublishSwitchRequest request = new BaselineScItemSpecPublishSwitchRequest();
            buildPublishSwitchRequest(request, scItemSDO, specGroupId, mnScItemUnitInfoSDO);
            Map result = (Map) baseDataService.baselineScItemSpecPublishSwitch(request);
            Boolean success = (Boolean) result.get("success");
            String message = (String) result.get("message");
            if(success!=null && !success){
                log.error("MnDataIf005V2ServiceImpl_ScItemSpecRelPublishSwitch_fail_req={},message={}", JSON.toJSONString(request),message);
            }
        } else {
            // 查到了oldList遍历,进来的这条数据是不是货品的基本规格  其中规格的单位、国际编码存在ScItemSpecSDO的extendFeatures中
            List<ScItemSpecSDO> scItemSpecSDOs = new ArrayList<>();
            for (Map map : scItemSpecSDOList) {
                ScItemSpecSDO scItemSpecSDO = JSON.parseObject(JSON.toJSONString(map), ScItemSpecSDO.class);
                scItemSpecSDOs.add(scItemSpecSDO);
            }
            String unitName = mnScItemUnitInfoSDO.getUnitName();
            List<ScItemSpecSDO> scItemSpecSDOBaseList = scItemSpecSDOs.stream().filter(it -> it.getSpecType().equals(1)).collect(Collectors.toList());
            List<ScItemSpecSDO> scItemSpecSDONormalList = scItemSpecSDOs.stream().filter(it -> it.getSpecType().equals(2)).collect(Collectors.toList());
            BaselineScItemSpecRelEditSwitchRequest editSwitchRequest = new BaselineScItemSpecRelEditSwitchRequest();
            if (unitName.equals(scItemSDO.getUnit())) {
                // 进来的就是基本单位
                buildEditSwitchRequest(editSwitchRequest, scItemSDO, specGroupId, mnScItemUnitInfoSDO, scItemSpecSDONormalList);
            } else {
                // 进来的数据不是基本数据,是普通数据
                buildRelEditSwitchRequest(editSwitchRequest, specGroupId, mnScItemUnitInfoSDO, scItemSpecSDOBaseList, scItemSpecSDONormalList, unitName);
            }
            Map result = (Map) baseDataService.baselineScItemSpecRelEditSwitch(editSwitchRequest);
            Boolean success = (Boolean) result.get("success");
            String message = (String) result.get("message");
            if(success!=null && !success){
                log.error("MnDataIf005V2ServiceImpl_ScItemSpecRelEditSwitch_fail_req={},message={}", JSON.toJSONString(editSwitchRequest),message);
            }
        }
        return true;
    }

    /**
     * 构造编辑箱规转换请求体
     * @param editSwitchRequest
     * @param specGroupId
     * @param mnScItemUnitInfoSDO
     * @param scItemSpecSDOBaseList
     * @param scItemSpecSDONormalList
     */
    private void buildRelEditSwitchRequest(BaselineScItemSpecRelEditSwitchRequest editSwitchRequest, String specGroupId,
                                           MnScItemUnitInfoSDO mnScItemUnitInfoSDO, List<ScItemSpecSDO> scItemSpecSDOBaseList,
                                           List<ScItemSpecSDO> scItemSpecSDONormalList, String unitName) {
        editSwitchRequest.setSpecGroupId(specGroupId);
        editSwitchRequest.setOperatorId("1000000001");
        // 基本单位转换信息不变
        BaseScItemSpecDTO baseScItemSpecDTO = new BaseScItemSpecDTO();
        ScItemSpecSDO specSDO = scItemSpecSDOBaseList.get(0);
        baseScItemSpecDTO.setScItemId(specSDO.getScItemId());
        baseScItemSpecDTO.setScItemType(specSDO.getScItemType());
        baseScItemSpecDTO.setRelationNum(specSDO.getRelationNum());
        Map map = new HashMap();
        // 单位名称
        map.put("unit", specSDO.getFeatures());
        // 获取到原extendFeatures
        String extendFeatures = specSDO.getExtendFeatures();
        ScItemSpecRelFeatures scItemSpecRelFeatures = JSONObject.parseObject(extendFeatures, ScItemSpecRelFeatures.class);
        // 单位编码
        String unitCode = scItemSpecRelFeatures.getUnitCode();
        if (StringUtils.isNotBlank(unitCode)) {
            map.put("unitCode", unitCode);
        }
        // 转换系数
        String conversion = scItemSpecRelFeatures.getConversion();
        if (StringUtils.isNotBlank(conversion)) {
            map.put("Conversion", conversion);
        }
        // 国际条码
        String internationalBarCode = scItemSpecRelFeatures.getInternationalBarCode();
        if (StringUtils.isNotBlank(internationalBarCode)) {
            map.put("internationalBarCode", internationalBarCode);
        }
        baseScItemSpecDTO.setFeatures(map);
        baseScItemSpecDTO.setId(specSDO.getSpecId());
        editSwitchRequest.setBaseScItemSpecDTO(baseScItemSpecDTO);
        // 查看普通单位转换关系存在不
        List<ScItemSpecSDO> sdo = scItemSpecSDONormalList
                .stream().filter(scItemSpecSDO -> scItemSpecSDO.getFeatures().equals(unitName)).collect(Collectors.toList());
        List<ScItemSpecSDO> sdoNo = scItemSpecSDONormalList
                .stream().filter(scItemSpecSDO -> !scItemSpecSDO.getFeatures().equals(unitName)).collect(Collectors.toList());
        // 存在  替换数据
        NormalScItemSpecDTO normalScItemSpecDTOEx = new NormalScItemSpecDTO();
        if (CollectionUtils.isNotEmpty(sdo)) {
            ScItemSpecSDO specSDOEdit = sdo.get(0);
            specSDOEdit.setScItemType(2);
            specSDOEdit.setRelationNum(Integer.valueOf(mnScItemUnitInfoSDO.getDenominator()));
            specSDOEdit.setFeatures(mnScItemUnitInfoSDO.getUnitName());
            BeanUtils.copyProperties(specSDOEdit, normalScItemSpecDTOEx);
            normalScItemSpecDTOEx.setId(specSDOEdit.getSpecId());
            Map mapEx = new HashMap();
            // 单位名称
            mapEx.put("unit", specSDOEdit.getFeatures());
            // 单位编码
            String unitCodeEdit = mnScItemUnitInfoSDO.getUnitCode();
            if (StringUtils.isNotBlank(unitCodeEdit)) {
                mapEx.put("unitCode", unitCodeEdit);
            }
            // 转换系数
            String conversionEdit = mnScItemUnitInfoSDO.getConversion();
            if (StringUtils.isNotBlank(conversionEdit)) {
                mapEx.put("Conversion", conversionEdit);
            }
            // 国际条码
            String internationalBarCodeEdit = mnScItemUnitInfoSDO.getInternationalBarCode();
            if (StringUtils.isNotBlank(internationalBarCodeEdit)) {
                mapEx.put("internationalBarCode", internationalBarCodeEdit);
            }
            normalScItemSpecDTOEx.setFeatures(mapEx);
        }
        // 不存在  新加进去
        else {
            normalScItemSpecDTOEx.setScItemType(2);
            normalScItemSpecDTOEx.setRelationNum(Integer.valueOf(mnScItemUnitInfoSDO.getDenominator()));
            Map mapEx = new HashMap();
            // 单位名称
            mapEx.put("unit", mnScItemUnitInfoSDO.getUnitName());
            // 单位编码
            mapEx.put("unitCode", mnScItemUnitInfoSDO.getUnitCode());
            // 转换系数
            mapEx.put("Conversion", mnScItemUnitInfoSDO.getConversion());
            // 国际条码
            if (StringUtils.isNotBlank(mnScItemUnitInfoSDO.getInternationalBarCode())) {
                mapEx.put("internationalBarCode", mnScItemUnitInfoSDO.getInternationalBarCode());
            }
            normalScItemSpecDTOEx.setFeatures(mapEx);
        }
        List<NormalScItemSpecDTO> collect = sdoNo.stream().map(scItemSpecSDO -> {
            NormalScItemSpecDTO normalScItemSpecDTO = new NormalScItemSpecDTO();
            BeanUtils.copyProperties(scItemSpecSDO, normalScItemSpecDTO);
            Map featureMap = new HashMap();
            // 单位名称
            featureMap.put("unit", scItemSpecSDO.getFeatures());
            // 获取到原extendFeatures
            String extendFeaturesOld = scItemSpecSDO.getExtendFeatures();
            ScItemSpecRelFeatures scItemSpecRelFeaturesOld = JSONObject.parseObject(extendFeaturesOld, ScItemSpecRelFeatures.class);
            // 单位编码
            String unitCodeOld = scItemSpecRelFeaturesOld.getUnitCode();
            if (StringUtils.isNotBlank(unitCodeOld)) {
                featureMap.put("unitCode", unitCodeOld);
            }
            // 转换系数
            String conversionOld = scItemSpecRelFeaturesOld.getConversion();
            if (StringUtils.isNotBlank(conversionOld)) {
                featureMap.put("Conversion", conversionOld);
            }
            // 国际条码
            String internationalBarCodeOld = scItemSpecRelFeaturesOld.getInternationalBarCode();
            if (StringUtils.isNotBlank(internationalBarCodeOld)) {
                featureMap.put("internationalBarCode", internationalBarCodeOld);
            }
            normalScItemSpecDTO.setFeatures(featureMap);
            normalScItemSpecDTO.setId(scItemSpecSDO.getSpecId());
            return normalScItemSpecDTO;
        }).collect(Collectors.toList());
        collect.add(normalScItemSpecDTOEx);
        editSwitchRequest.setNormalScItemSpecDTOs(collect);
    }

    /**
     * 构造发布单位转换关系请求体
     * @param publishSwitchRequest
     * @param scItemSDO
     * @param specGroupId
     * @param mnScItemUnitInfoSDO
     */
    private void buildPublishSwitchRequest(BaselineScItemSpecPublishSwitchRequest publishSwitchRequest,
                                           ScItemSDO scItemSDO, String specGroupId, MnScItemUnitInfoSDO mnScItemUnitInfoSDO) {
        publishSwitchRequest.setSpecGroupId(specGroupId);
        BaseScItemSpecDTO baseScItemSpecDTO = new BaseScItemSpecDTO();
        // 基本单位的单位转换关系是真实的scItemId
        baseScItemSpecDTO.setScItemId(scItemSDO.getScItemId());
        // 真实货品就是主打货品
        baseScItemSpecDTO.setScItemType(1);
        baseScItemSpecDTO.setRelationNum(1);
        Map map = new HashMap();
        // 存在客户的部分数据（例如：奶卡套餐.....，只有单位编码，没有单位名称，需要根据编码查一下名称）
        String unitNameDesc = scItemSDO.getUnit();
        Map<String, String> features = scItemSDO.getFeatures();
        String unitNameCode = features.get("unitName");
        if (StringUtils.isBlank(unitNameDesc) && StringUtils.isNotBlank(unitNameCode)) {
            ScItemUnitLoadListRequest scItemUnitLoadListRequest = new ScItemUnitLoadListRequest();
            scItemUnitLoadListRequest.setCode(unitNameCode);
            Result<List<ScItemUnit>> loadScItemUnitResult = scItemUnitService.loadScItemUnitList(scItemUnitLoadListRequest);
            List<ScItemUnit> scItemUnitList = loadScItemUnitResult.getResult();
            if (CollectionUtils.isNotEmpty(scItemUnitList)) {
                ScItemUnit scItemUnit = scItemUnitList.get(0);
                unitNameDesc = scItemUnit.getName();
            }
        }
        // 单位名称
        map.put("unit", unitNameDesc);
        // 单位编码
        map.put("unitCode", unitNameCode);
        // 判断进来的这条数据是普通规格还是基本规格
        List<NormalScItemSpecDTO> normalScItemSpecDTOList = new ArrayList<>();
        String unitName = mnScItemUnitInfoSDO.getUnitName();
        // 1 进来的是普通规格(再构造普通规格)  进来的是基本规格的话,普通规格为空
        if (!unitName.equals(scItemSDO.getUnit())) {
            NormalScItemSpecDTO normalScItemSpecDTO = new NormalScItemSpecDTO();
            normalScItemSpecDTO.setScItemType(2);
            normalScItemSpecDTO.setRelationNum(Integer.valueOf(mnScItemUnitInfoSDO.getDenominator()));
            Map map1 = new HashMap();
            // 单位名称
            map1.put("unit", mnScItemUnitInfoSDO.getUnitName());
            // 单位编码
            map1.put("unitCode", mnScItemUnitInfoSDO.getUnitCode());
            // 转换系数
            map1.put("Conversion", mnScItemUnitInfoSDO.getConversion());
            // 国际条码
            if (StringUtils.isNotBlank(mnScItemUnitInfoSDO.getInternationalBarCode())) {
                map1.put("internationalBarCode", mnScItemUnitInfoSDO.getInternationalBarCode());
            }
            normalScItemSpecDTO.setFeatures(map1);
            normalScItemSpecDTOList.add(normalScItemSpecDTO);
        }
        // 进来的是基本规格
        else {
            // 单位编码
            map.put("unitCode", mnScItemUnitInfoSDO.getUnitCode());
            // 转换系数
            map.put("Conversion", mnScItemUnitInfoSDO.getConversion());
            // 国际条码
            if (StringUtils.isNotBlank(mnScItemUnitInfoSDO.getInternationalBarCode())) {
                map.put("internationalBarCode", mnScItemUnitInfoSDO.getInternationalBarCode());
            }
        }
        baseScItemSpecDTO.setFeatures(map);
        publishSwitchRequest.setBaseScItemSpecDTO(baseScItemSpecDTO);
        publishSwitchRequest.setOperatorId("1000000001");
        publishSwitchRequest.setNormalScItemSpecDTOs(normalScItemSpecDTOList);
    }

    /**
     * 构造编辑箱规转换关系
     * @param editSwitchRequest
     * @param scItemSDO
     * @param specGroupId
     * @param mnScItemUnitInfoSDO
     * @param scItemSpecSDONormalList
     */
    private void buildEditSwitchRequest(BaselineScItemSpecRelEditSwitchRequest editSwitchRequest, ScItemSDO scItemSDO,
                                        String specGroupId, MnScItemUnitInfoSDO mnScItemUnitInfoSDO,
                                        List<ScItemSpecSDO> scItemSpecSDONormalList) {
        // 变更的基本单位转换关系去构造
        editSwitchRequest.setSpecGroupId(specGroupId);
        editSwitchRequest.setOperatorId("1000000001");
        BaseScItemSpecDTO baseScItemSpecDTO = new BaseScItemSpecDTO();
        baseScItemSpecDTO.setScItemId(scItemSDO.getScItemId());
        baseScItemSpecDTO.setScItemType(1);
        baseScItemSpecDTO.setRelationNum(Integer.valueOf(mnScItemUnitInfoSDO.getDenominator()));
        Map baseMapFeatures = new HashMap();
        // 单位名称
        baseMapFeatures.put("unit", mnScItemUnitInfoSDO.getUnitName());
        // 单位编码
        baseMapFeatures.put("unitCode", mnScItemUnitInfoSDO.getUnitCode());
        // 转换系数
        baseMapFeatures.put("Conversion", mnScItemUnitInfoSDO.getConversion());
        // 国际条码
        if (StringUtils.isNotBlank(mnScItemUnitInfoSDO.getInternationalBarCode())) {
            baseMapFeatures.put("internationalBarCode", mnScItemUnitInfoSDO.getInternationalBarCode());
        }
        baseScItemSpecDTO.setFeatures(baseMapFeatures);
        editSwitchRequest.setBaseScItemSpecDTO(baseScItemSpecDTO);
        // 普通单位转换关系不变
        List<NormalScItemSpecDTO> normalScItemSpecDTOs = scItemSpecSDONormalList.stream().map(scItemSpecSDO -> {
            NormalScItemSpecDTO normalScItemSpecDTO = new NormalScItemSpecDTO();
            normalScItemSpecDTO.setScItemType(scItemSpecSDO.getScItemType());
            normalScItemSpecDTO.setRelationNum(scItemSpecSDO.getRelationNum());
            Map<String, String> map = new HashMap();
            // 单位名称
            map.put("unit", scItemSpecSDO.getFeatures());
            // 获取到原extendFeatures
            String extendFeatures = scItemSpecSDO.getExtendFeatures();
            ScItemSpecRelFeatures scItemSpecRelFeatures = JSONObject.parseObject(extendFeatures, ScItemSpecRelFeatures.class);
            // 单位编码
            String unitCode = scItemSpecRelFeatures.getUnitCode();
            if (StringUtils.isNotBlank(unitCode)) {
                map.put("unitCode", unitCode);
            }
            // 转换系数
            String conversion = scItemSpecRelFeatures.getConversion();
            if (StringUtils.isNotBlank(conversion)) {
                map.put("Conversion", conversion);
            }
            // 国际条码
            String internationalBarCode = scItemSpecRelFeatures.getInternationalBarCode();
            if (StringUtils.isNotBlank(internationalBarCode)) {
                map.put("internationalBarCode", internationalBarCode);
            }
            normalScItemSpecDTO.setFeatures(map);
            return normalScItemSpecDTO;
        }).collect(Collectors.toList());
        editSwitchRequest.setNormalScItemSpecDTOs(normalScItemSpecDTOs);
    }

    /**
     * 保存单位库
     * @param mnScItemUnitInfoSDO
     * @return
     */
    private String saveScItemUnit(MnScItemUnitInfoSDO mnScItemUnitInfoSDO) {
        // 1、查询单位库
        ScItemUnitLoadListRequest scItemUnitLoadListRequest = new ScItemUnitLoadListRequest();
        scItemUnitLoadListRequest.setCode(mnScItemUnitInfoSDO.getUnitCode());
        Result<List<ScItemUnit>> loadScItemUnitResult = scItemUnitService.loadScItemUnitList(scItemUnitLoadListRequest);
        List<ScItemUnit> scItemUnitList = loadScItemUnitResult.getResult();
        String unitId;

        // 2、更新单位库
        if (CollectionUtils.isNotEmpty(scItemUnitList)) {
            ScItemUnit updateScItemUnit = new ScItemUnit();
            ScItemUnit scItemUnit = scItemUnitList.get(0);
            updateScItemUnit.setId(scItemUnit.getId());
            updateScItemUnit.setCode(mnScItemUnitInfoSDO.getUnitCode());
            updateScItemUnit.setDesc(mnScItemUnitInfoSDO.getUnitDesc());
            updateScItemUnit.setName(mnScItemUnitInfoSDO.getUnitName());
            updateScItemUnit.setOutCode(mnScItemUnitInfoSDO.getUnitCode());
            updateScItemUnit.setOutName(mnScItemUnitInfoSDO.getUnitName());
            updateScItemUnit.setUpdater("1000000001");
            updateScItemUnit.setGmtModified(new Date());
            UpdateScItemUnitResponse updateScItemUnitResponse = scItemUnitService.updateScItemUnit(updateScItemUnit);
            if (!(updateScItemUnitResponse.getCount() > 0)) {
                throw new RuntimeException("编辑单位库信息异常");
            }
            unitId = scItemUnit.getId().toString();
        }
        // 3、新增单位库
        else {
            ScItemUnit createScItemUnit = new ScItemUnit();
            createScItemUnit.setCode(mnScItemUnitInfoSDO.getUnitCode());
            createScItemUnit.setDesc(mnScItemUnitInfoSDO.getUnitDesc());
            createScItemUnit.setName(mnScItemUnitInfoSDO.getUnitName());
            createScItemUnit.setOutCode(mnScItemUnitInfoSDO.getUnitCode());
            createScItemUnit.setOutName(mnScItemUnitInfoSDO.getUnitName());
            createScItemUnit.setCreator("1000000001");
            createScItemUnit.setGmtCreate(new Date());
            CreateScItemUnitResponse createScItemUnitResponse = scItemUnitService.createScItemUnit(createScItemUnit);
            // 这个字段要放在转换关系表的features中   保存单位编码和名称
            unitId = createScItemUnitResponse.getLastInsertId();
            itemDataChangeMessage(mnScItemUnitInfoSDO.getUnitCode(), "CREATE_EVENT");
        }
        return unitId;
    }

    /**
     * 保存规格组
     * @param scItemSDO
     * @return
     */
    private String saveScItemSpecGroup(ScItemSDO scItemSDO) {
        String title = scItemSDO.getTitle();
        // 根据名称全搜索
//        BaselineQueryItemSpecListRequest baselineQueryItemSpecListRequest = new BaselineQueryItemSpecListRequest();
//        baselineQueryItemSpecListRequest.setSpecGroupNameAccurate(title + "规格组");
//        BaselineQueryItemSpecListResponse baselineQueryItemSpecListResponse = baseDataService.baselineQueryItemSpecList(baselineQueryItemSpecListRequest);

//        BaselineQueryRelationSpecRequest baselineQueryRelationSpecRequest = new BaselineQueryRelationSpecRequest();
//        baselineQueryRelationSpecRequest.setScItemId(scItemSDO.getScItemId());
//        BaselineQueryRelationSpecResponse baselineQueryRelationSpecResponse = baseDataService.baselineQueryRelationSpec(baselineQueryRelationSpecRequest);
//        if (null == baselineQueryRelationSpecResponse || null == baselineQueryRelationSpecResponse.getResult()) {
//            log.error("获取规格组异常");
//            return null;
//        }
//        Map result = (Map) baselineQueryRelationSpecResponse.getResult();
//        List<Map<String, Object>> scItemSpecList = (List<Map<String, Object>>) result.get("scItemSpecSDOList");
        //一个货品对应一个规格组，一个规格组至少有一个基本规格
        BaselineQueryRelationSpecRequest baselineQueryRelationSpecRequest = new BaselineQueryRelationSpecRequest();
        baselineQueryRelationSpecRequest.setScItemId(scItemSDO.getScItemId());
        BaselineQueryRelationSpecResponse baselineQueryRelationSpecResponse = baseDataService.baselineQueryRelationSpec(baselineQueryRelationSpecRequest);
        if (null == baselineQueryRelationSpecResponse || null == baselineQueryRelationSpecResponse.getResult()) {
            log.info("获取规格组异常");
            return null;
        }
        Map queryResult = (Map) baselineQueryRelationSpecResponse.getResult();
        List<Map<String, Object>> scItemSpecList = (List<Map<String, Object>>) queryResult.get("scItemSpecSDOList");
        log.info("MnDataIf005V2ServiceImpl_saveScItemUnitInfo_query_request={},result_list={}", JSONObject.toJSON(baselineQueryRelationSpecRequest), JSONObject.toJSON(scItemSpecList));
        String specGroupId;
        // 规格组为空 创建规格组
        if (CollectionUtils.isEmpty(scItemSpecList)) {
            BaselineAddItemSpecRequest baselineAddItemSpecRequest = new BaselineAddItemSpecRequest();
            baselineAddItemSpecRequest.setSpecGroupName(title + "规格组");
            baselineAddItemSpecRequest.setBusinessType("11");
            baselineAddItemSpecRequest.setBusinessTypeName("常温");
            baselineAddItemSpecRequest.setFromSys("DC");
            Map addItemSpec = (Map)baseDataService.baselineAddItemSpec(baselineAddItemSpecRequest);
            log.info("MnDataIf005V2ServiceImpl_saveScItemSpecGroup_request={},result={}", JSONObject.toJSON(baselineAddItemSpecRequest), JSONObject.toJSON(addItemSpec));
            DubboResult addItemSpecResult = null;
            try {
                addItemSpecResult = ResultUtils.getDubboPageResult(addItemSpec);
            } catch (Exception e) {
                log.info("MnDataIf005V2ServiceImpl_saveScItemSpecGroup_error_item={},error={}", title, e.getMessage());
                //没有规格转换关系，但是呢有对应规格组
                if(e.getMessage().contains("名称重复")){
                    BaselineQueryItemSpecListRequest baselineQueryItemSpecListRequest = new BaselineQueryItemSpecListRequest();
                    baselineQueryItemSpecListRequest.setSpecGroupNameAccurate(title + "规格组");
                    BaselineQueryItemSpecListResponse baselineQueryItemSpecListResponse = baseDataService.baselineQueryItemSpecList(baselineQueryItemSpecListRequest);
                    if (null == baselineQueryItemSpecListResponse || null == baselineQueryItemSpecListResponse.getResult()) {
                        log.info("获取规格组异常");
                        return null;
                    }
                    Map result = (Map) baselineQueryItemSpecListResponse.getResult();
                    Map map = (Map) result.get("result");
                    if (null == map) {
                        log.info("获取规格组异常");
                        return null;
                    }
                    Object scItemSpecGroupSearchDTOS = map.get("scItemSpecGroupSearchDTOS");
                    List<Map<String, Object>> tempList= (List<Map<String, Object>>)scItemSpecGroupSearchDTOS;
                    Map<String, Object> scItemSpecMap = tempList.get(0);
                    Object itemSpecGroupSDO = scItemSpecMap.get("scItemSpecGroupSDO");
                    ScItemSpecGroupSDO scItemSpecGroupSDO = JSON.parseObject(JSON.toJSONString(itemSpecGroupSDO), ScItemSpecGroupSDO.class);
                    specGroupId = scItemSpecGroupSDO.getSpecGroupId();
                    log.info("MnDataIf005V2ServiceImpl_saveScItemSpecGroup_repeatScItemSpecGroup_item={},specGroupId={}", title,specGroupId);
                    return specGroupId;
                }
            }
            Map addItemSpecMap = (Map) addItemSpec.get("result");
            Map result1 = (Map) addItemSpecMap.get("result");
            specGroupId = result1.get("specGroupId").toString();
        } else {
            Map<String, Object> scItemSpecMap = scItemSpecList.get(0);
            specGroupId = (String) scItemSpecMap.get("specGroupId");
            BaselineEditItemSpecRequest baselineEditItemSpecRequest = new BaselineEditItemSpecRequest();
            baselineEditItemSpecRequest.setSpecGroupId(specGroupId);
            baselineEditItemSpecRequest.setSpecGroupName(title + "规格组");
            Map editItemSpec = (Map)baseDataService.baselineEditItemSpec(baselineEditItemSpecRequest);
            log.info("MnDataIf005V2ServiceImpl_saveScItemSpecGroup_edit_request={},result={}", JSONObject.toJSON(baselineEditItemSpecRequest), JSONObject.toJSON(editItemSpec));
            DubboResult editItemSpecResult = null;
            try {
                editItemSpecResult = ResultUtils.getDubboResult(editItemSpec);
            } catch (Exception e) {
                log.info("MnDataIf005V2ServiceImpl_saveScItemSpecGroup_edit_error_item={},error={}", title, e.getMessage());
            }
        }
        return specGroupId;
    }

    private void itemDataChangeMessage(String key, String eventCode) {
        try {
            log.info("MnDataIf005V2ServiceImpl_itemDataChangeMessage_key:{},eventCode:{}", key, eventCode);
            ItemCenterDataChangeMessageRequest request = new ItemCenterDataChangeMessageRequest();
            request.setKeyword(key);
            request.setBusinessCode("UNIT");
            request.setEventCode(eventCode);
            request.setEventTime(new Date());
            request.setFromSys("DC");
            dpService.itemCenterDataChangeMessage(request);
        } catch (Exception e) {
            log.error("MnDataIf005V2ServiceImpl_itemDataChangeMessage:", e);
        }
    }
}